/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.manage.admin.config;

import cn.hutool.core.collection.CollUtil;
import cn.zmwh.manage.admin.modules.sync.ProductBinlogEventHandler;
import com.gitee.Jmysy.binlog4j.core.BinlogClient;
import com.gitee.Jmysy.binlog4j.core.BinlogClientConfig;
import com.gitee.Jmysy.binlog4j.core.config.RedisConfig;
import com.gitee.Jmysy.binlog4j.core.enums.BinlogClientMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @describe: 、
 * @author: dmzmwh 、
 * @time: 2025-03-29 15:29 、
 */
@Configuration
public class BinlogClientRegisterConfig implements ApplicationRunner {

    @Autowired
    private RedisProperties redisProperties;
    @Autowired
    private Binlog4jProperties binlog4jProperties;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        RedisConfig redisConfig = new RedisConfig();
        redisConfig.setHost(redisProperties.getHost());
        redisConfig.setPort(redisProperties.getPort());
        redisConfig.setPassword(redisProperties.getPassword());
        redisConfig.setDatabase(15);

        List<BinlogClientConfig> products = binlog4jProperties.getProducts();
        if (CollUtil.isEmpty(products)) {
            return;
        }
        //多数据源时多个client
        for (BinlogClientConfig product : products) {
            BinlogClientConfig productClientConfig = new BinlogClientConfig();
            productClientConfig.setRedisConfig(redisConfig);
            productClientConfig.setHost(product.getHost());
            productClientConfig.setPort(3306);
            productClientConfig.setUsername(product.getUsername());
            productClientConfig.setPassword(product.getPassword());
            productClientConfig.setPersistence(true); // 开启续读
            productClientConfig.setServerId(1990);//集群模式必须指定
            productClientConfig.setMode(BinlogClientMode.standalone);//单机部署
            BinlogClient productClient = new BinlogClient(productClientConfig);
            productClient.registerEventHandler(new ProductBinlogEventHandler());
            productClient.connect();
        }

    }

}
